// index.js
//导入utils包的相关连接
var FormData = require('../../utils/formData.js');
var util = require('../../utils/util.js');
var app = getApp();
Page({
  data: {
    phone: '',
    res: '',
    code: '',
    math: '',
    yzm: '获取验证码',
    num: 60,
    i: 0,
    submit:"submit",
    //隐藏图标信息
    dialog: {
      hidden: true
    },
    dialog1: {
      hidden: true
    },
    dialog2: {
      hidden: true
    },
    dialog3: {
      hidden: true
    },
    dialog4: {
      hidden: true
    },
  },
  globalData: {
    isLogin: false,
    userInfo: {},
    jscode: null,
    serverRootUrl: "https://wwl.ycws.cc/wxpay",
    head: {
      version: "v1.0",
      clientType: "wxxcx",
      apikey: "*****f",
      userId: null,
      resCode: null,
      cmdId: ""
    },
    rawData: null,
    encryptedData: null,
    iv: null,
    signature: null,
    picRootUrl: null,
    openId: null,
    freeFreightFee: null,
    freight: null,
    phone: null
  },
  onLoad: function (options) {
  /**  var that=this;
    that.setData({submit:"submit"});
    //页面自动加载
    console.log("页面自动加载123");
    this.login();*/
    // var openid = wx.getStorageSync("developer");
    // wx.request({
    //   url: "https://wwl.ycws.cc/wxpay/SelectOpenId/SelectOpenidfinto", 
    //   //url: "https://wwl.ycws.cc/wxpay/SelectOpenId/SelectOpenidfinto", 
    //   method:"post",
    //   header: { 'content-type': 'application/x-www-form-urlencoded' },
    //   data: { typeber: "1", openidma: openid },
    //   success: function (data) {
       
    //     var net=data.data.number;
    //     if(net=="1"){
    //       console.log("已经注册了用户的数据")
    //     }else if(net=="2"){
    //       console.log("没有注册过用户数据")
    //     }
    //   },
    //   error: function (date) {
    //     console.log("网络异常，请联系开发商")
    //   }
    // })
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  /*
    1.触动手机号码事件
    2.根据输入的手机号码获取对应数字，并保存
  */
  phoneDataChange: function (e) {
    var phone = e.detail.value;
    this.data.phone = phone;
  },

  /**
   * 1.调用toast方法,设置多少秒后自动消失
   */
  toastChange: function (e) {
    this.setData({
      dialog: {
        hidden: true
      }
    });

  },
  toast1Change: function (e) {
    this.setData({
      dialog1: {
        hidden: true
      }
    });

  },
  toast2Change: function (e) {
    this.setData({
      dialog2: {
        hidden: true
      }
    });
  },
  toast4Change: function (e) {
    this.setData({
      dialog4: {
        hidden: true
      }
    });
  },
  
  /*
    1.触动获取验证码事件
    2.随机生成4位验证码
    3.使用正则表达式判断手机号码是否是1数字开头共11位,是则通过发送验证码,不是则提示手机号码不符合
    4.根据输入的11位手机号码调用235网站短信接口进行发送
    5.使用json格式传递账号，密码，内容等信息
  */
  time: function () {
    var that = this;
    var i = that.data.num;
    if (i == 60) {
      this.cutdown(this);
    }
  },
  cutdown: function () {
    var that = this;
    var n = that.data.num - 1
    that.setData({
      num: n,
      yzm: n
    })
    if (n > 0) {
      setTimeout(function () {
        that.cutdown(that);
      }, 1000)
    }
    if (n <= 0) {
      that.setData({
        yzm: "请重新获取",
        num: 60
      });
    }
    return;
  },
  getVerifyCode: function () {
    if (!util.validatePhone(this.data.phone)) {
      console.log("手机号码为空");
    } else {
      this.time();
    }
    var that = this;
    if (!util.validatePhone(this.data.phone)) {
      that.setData({ 'dialog2.hidden': false })
    }
    console.log("----" + this.data.yzm + "---");
    if (this.data.yzm == 59) {
      var maths = 0;
      while (maths < 1000) {
        maths = Math.round(Math.random() * 10000);
      }
      this.data.math = maths;
      var formData = this.data.phone;
      console.log("手机号码" + formData + "接收的验证码是" + this.data.math);
      wx.request({
        url: 'https://imlaixin.cn/Api/send/data/json',
        method: 'GET',
        data: {
          mobile: formData,
          accesskey: '1861',
          secretkey: 'c2d829b888f73073de0af3f6653d23c7ae8ec2c9',
          //content: '验证码:' + this.data.math + '【万物联】',
          content: '欢迎使用人脸识别系统，验证码:' + this.data.math + '【彩生活e安全】',
        },
        header: {
          'content-type': 'application/json'
        },
      });
    } else if (this.data.yzm == '请重新获取') {
      that.time();
    }
  },
  /*
    1.触动登录事件
    2.根据e.detail.value["code"]获取文本框输入的信息和随机数进行对比,数字一致则提示登录成功跳转到下一个页面,否则提示验证码有误
   */
  formSubmit: function (e) {
    var that = this;
    var math = this.data.math;
    var phone = e.detail.value["phone"];
    var code = e.detail.value["code"];

    if (e.detail.value["code"] != "" && this.data.math == e.detail.value["code"]) {
      that.setData({ 'dialog1.hidden': true })
      wx.request({
        url: 'https://wwl.ycws.cc/ssm/owner/newselectPhone', //查询手机号码
        data: {
          yphone: phone,
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          if (res.data.result == "查询失败") {
            wx.request({
              url: 'https://wwl.ycws.cc/ssm/owner/addPhone', //添加手机号码
              data: {
                yphone: res.data.yphone
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                console.log(res.data);
                console.log(res.data.uploadfiles[0].ynumber)
                var y=res.data.uploadfiles[0].ynumber;
                app.owner.ynumber = y;
                console.log("y----" + app.owner.ynumber)
                

                 wx.redirectTo({
                  url: '../adduser/adduser' 
                 })
              }
            })
          } else {
            app.owner.phone = phone;
            wx.redirectTo({
              url: '../showuser/showuser'
            })
          }
        },
        fail: function (res) {
          console.log("查询失败");
        }
      })
    } else {
      that.setData({ 'dialog1.hidden': false })
    }
  },
  login: function (e) {
    var that = this
    //登录成功，设置登录数据
    function setUserData(data) {
      console.info(data)
      if (data.head.resCode == 0) {
        that.globalData.head.userId = data.body.userInfo.id,
          that.globalData.picRootUrl = data.body.picRoot,
          that.globalData.userInfo = data.body.userInfo,
          that.globalData.isLogin = true,
          that.globalData.openId = data.body.openId,
          that.globalData.freeFreightFee = data.body.freeFreightFee,
          that.globalData.freight = data.body.freight
      } else {
        that.globalData.picRootUrl = data.body.picRoot,
          that.globalData.freeFreightFee = data.body.freeFreightFee,
          that.globalData.freight = data.body.freight
      }
    }
    function setWxLoginData(res) {
      that.globalData.userInfo = res.userInfo
      that.globalData.rawData = res.rawData
      that.globalData.encryptedData = res.encryptedData
      that.globalData.iv = res.iv,
        that.globalData.signature = res.signature
    }
    //登录
    wx.login({
      success: function (res) {
        that.globalData.jscode = res.code
        wx.getUserInfo({
          success: function (res) {
            //success
            setWxLoginData(res)
            requestBaseData();
          }
        })
      }
    })
    //请求服务器数据
    function requestBaseData() {
      var bodydata = {
        wxLoginCode: that.globalData.jscode,
        nickName: encodeURIComponent(that.globalData.userInfo.nickName),
        avatarUrl: that.globalData.userInfo.avatarUrl,
        gender: that.globalData.userInfo.gender,
        province: that.globalData.userInfo.province,
        city: that.globalData.userInfo.city,
        country: that.globalData.userInfo.country,
        rawData: encodeURIComponent(that.globalData.rawData),
        signature: that.globalData.signature,
        encryptedData: that.globalData.encryptedData,
        iv: that.globalData.iv,
        phone: that.globalData.phone

      }
      wx.request({
        url: 'https://wwl.ycws.cc/wxpay/launch/base',
        data: {
          head: that.globalData.head,
          body: bodydata
        },
        //header: {}, // 设置请求的 header
        method: 'GET',
        success: function (res) {
          setUserData(res.data)
          console.log(res.data);
          wx.request({
            url: 'https://wwl.ycws.cc/ssm/owner/selectOpenid',
            data: {
              openid: res.data.body.openId
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              if (res.data == null) {
                console.log('不存在');
              } else {
                console.log(res.data.ynumber)
                app.owner.phone = res.data.yphone;
                wx.redirectTo({
                  url: '../showuser/showuser'
                })
              }
            }
          })
        }
      })
    }
  },
  userNamephone: function (e) {
    this.setData({
      userNamephone: e.detail.value
    })
  },

  login1: function (e) {
    this.setData({ 'dialog3.hidden': false });
    var that = this
    var math = this.data.math;
    //var code = e.detail.value["code"];
    //var phone = e.detail.value["phone"];
    var phone = this.data.userNamephone;
    //登录成功，设置登录数据
    function setUserData(data) {
      console.info(data)
      if (data.head.resCode == 0) {
        that.globalData.head.userId = data.body.userInfo.id,
          that.globalData.picRootUrl = data.body.picRoot,
          that.globalData.userInfo = data.body.userInfo,
          that.globalData.isLogin = true,
          that.globalData.openId = data.body.openId,
          that.globalData.freeFreightFee = data.body.freeFreightFee,
          that.globalData.freight = data.body.freight
      } else {
        that.globalData.picRootUrl = data.body.picRoot,
          that.globalData.freeFreightFee = data.body.freeFreightFee,
          that.globalData.freight = data.body.freight
      }
    }
    function setWxLoginData(res) {
      that.globalData.userInfo = res.userInfo
      that.globalData.rawData = res.rawData
      that.globalData.encryptedData = res.encryptedData
      that.globalData.iv = res.iv,
      that.globalData.signature = res.signature
    }
    //登录
    wx.login({
      success: function (res) {
        that.globalData.jscode = res.code
        wx.getUserInfo({
          success: function (res) {
            //success
            setWxLoginData(res)
            requestBaseData();
          }
        })
      }
    })
    //请求服务器数据
    function requestBaseData() {
      var bodydata = {
        wxLoginCode: that.globalData.jscode,
        nickName: encodeURIComponent(that.globalData.userInfo.nickName),
        avatarUrl: that.globalData.userInfo.avatarUrl,
        gender: that.globalData.userInfo.gender,
        province: that.globalData.userInfo.province,
        city: that.globalData.userInfo.city,
        country: that.globalData.userInfo.country,
        rawData: encodeURIComponent(that.globalData.rawData),
        signature: that.globalData.signature,
        encryptedData: that.globalData.encryptedData,
        iv: that.globalData.iv,
        phone: phone
      }
      //判断手机号码是否存在
      //if (code != "" && math == code) {
       // that.setData({ 'dialog1.hidden': true })
      if (!util.validatePhone(phone)){
        that.setData({ 'dialog2.hidden': false })
        that.setData({ 'dialog3.hidden': true })
       }else{
        wx.request({
          url: 'https://wwl.ycws.cc/ssm/owner/newselectPhone', //查询手机号码
          data: {
            yphone: phone,
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {

            
            that.setData({ submit: "none" });
            console.log(res.data)
            if (res.data.result == "查询失败") {
              console.log("查询失败");
              wx.request({
                url: 'https://wwl.ycws.cc/wxpay/launch/base',
                data: {
                  head: that.globalData.head,
                  body: bodydata
                },
                // header: {}, // 设置请求的 header
                method: 'GET',
                success: function (res) {
                  setUserData(res.data)
                  console.log(res.data);
                  wx.request({
                    url: 'https://wwl.ycws.cc/ssm/owner/selectOnePhone',
                    data: {
                      yphone: phone
                    },
                    header: {
                      'content-type': 'application/json'
                    },
                    success: function (res) {
                      console.log(res.data)
                      app.owner.ynumber = res.data.ynumber;
                      if (app.owner.ynumber!=null){
                        wx.redirectTo({
                        url: '../adduser/adduser'
                        })
                      }else{
                        that.setData({ 'dialog4.hidden': false })
                      }
                    }
                  })
                }
              })
            } else {
              //console.log("-----showuser-------" + phone);
              app.owner.phone = phone;
              wx.redirectTo({
                url: '../showuser/showuser'
             })
            }
          },
        })
       }
    }
  },
  Intset:function(){
    var customer_no = wx.getStorageSync("developer");
    var phone = this.data.userNamephone;
    //var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!util.validatePhone(phone)){
      console.log("请输入正确的手机号码")
    } else if (!util.validatePhone(phone)){
      console.log("请输入手机号码")
    }else{
      var data = { phone: phone, customer_no: customer_no}
      util.ajax("post", "/smallRoutineController/Insetidentity", data, function (data) {
        if (data.returnMsg.cookma == "200"){
          if (data.returnMsg.ynumber == "00"){
            var phoneto = data.returnMsg.yphone
            wx.navigateTo({
              url: '../adduser/adduser?phoneto=' + phoneto
            })
          } else if (data.returnMsg.ynumber == "01"){
              console.log("手机号码已经存在")
          } else if (data.returnMsg.ynumber=="10"){
              console.log("提交异常")
          }

        }else{
            console.log("程序异常")
        }
      })
    }
  }
})

